/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serverapplication;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A simple database source for getting database connection
 * Also stores the global variable of DB connection
 * @author 王舒嶷
 */
public class DataBaseConnectionSource {

    /* Initializes the datbase connection source
     * @param fileName the name of property file that contains the database driver, URL, username and password
     * 
     */
    public static void init(String fileName) throws IOException, ClassNotFoundException {
//        Properties props = new Properties();
//        FileInputStream in = new FileInputStream(fileName);
//        props.load(in);
//        String driver = props.getProperty("jdbc.driver");
//        url = props.getProperty("jdbc.url");
//        username = props.getProperty("jdbc.username");
//        if (username == null) {
//            username = "";
//        }
//        password = props.getProperty("jdbc.password");
//        if (password == null) {
//            password = "";
//        }

        //for test purpose only
        String driver = "com.mysql.jdbc.Driver";
        url = "jdbc:mysql://localhost:3306/test_clickkit";
        username = "root";
        password = "19910209";
        //test only


        if (driver != null) {
            Class.forName(driver);
        }



    }

    /*
     * Gets a connction to the database
     * @return the database connection
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
    private static String url;
    private static String username;
    private static String password;
    public static Lock databaseLock = new ReentrantLock();
    public static Connection conn = null;
}
